using BasicData.ErrorCode;
using Microsoft.AspNetCore.Mvc;

namespace BasicData.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ImageController : ControllerBase
    {
        private readonly QiniuUploadService _qiniuUploadService;
        private readonly ILogger<ImageController> _logger;

        public ImageController(QiniuUploadService qiniuUploadService, ILogger<ImageController> logger)
        {
            _qiniuUploadService = qiniuUploadService;
            _logger = logger;
        }

        /// <summary>
        /// 上传单个图片到七牛云
        /// </summary>
        /// <param name="file">图片文件</param>
        /// <returns>图片访问路径</returns>
        [HttpPost("upload")]
        public async Task<APIResult<string>> UploadImage(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new APIResult<string>
                {
                    Code = ResultCode.添加失败,
                    Message = "请选择要上传的文件"
                };
            }

            // 检查文件类型
            var extension = Path.GetExtension(file.FileName).ToLowerInvariant();
            string[] allowedExtensions = { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
            if (!Array.Exists(allowedExtensions, ext => ext == extension))
            {
                return new APIResult<string>
                {
                    Code = ResultCode.添加失败,
                    Message = "只允许上传jpg、jpeg、png、gif、bmp格式的图片"
                };
            }

            // 检查文件大小（限制为5MB）
            if (file.Length > 5 * 1024 * 1024)
            {
                return new APIResult<string>
                {
                    Code = ResultCode.PARAM_ERROR,
                    Message = "图片大小不能超过5MB"
                };
            }

            try
            {
                // 生成唯一文件名
                var fileName = $"{Guid.NewGuid()}{extension}";

                // 上传到七牛云
                using var stream = file.OpenReadStream();
                var (success, url, message) = await _qiniuUploadService.UploadFileAsync(stream, fileName);

                if (success)
                {
                return new APIResult<string>
                {
                        Code = ResultCode.添加成功,
                    Message = "上传成功",
                        Data = url
                };
            }
                else
            {
                return new APIResult<string>
                {
                        Code = ResultCode.添加失败,
                        Message = message
                };
            }

                    }
                catch (Exception ex)
                {
                _logger.LogError(ex, "上传图片时发生异常");
                return new APIResult<string>
            {
                    Code = ResultCode.添加失败,
                    Message = $"上传失败: {ex.Message}"
                    };
                }
            }
        }
